<template>
  <div class="user-w">
    <!-- search -->
    <Search @update:model-value="search" @clear="clear" v-model="value" placeholder="搜索：用户名字" />

    <!-- 主要内容入口 -->
    <!--<RouterView @set="getDeptName" />-->
    <div class="list">
      <Cell v-if="userList?.length > 0" class="dept" v-for="(item, index) in userList" @click="setDeptItem(item)" :key="index">
        <Checkbox v-model="item.checked">
          <div class="user">
            <!-- header -->
            <Image class="img" width="0.9rem" height="0.9rem" :src="item.img"></Image>
            <!-- info -->
            <div class="user-items">
              <div>
                <span class="name" v-if="item.userName">{{ item?.userName }} </span>
              </div>
              <span class="depts">{{ item.createTime }}</span>
            </div>
          </div>
        </Checkbox>
      </Cell>
      <Empty v-else class="mt3" image-size="80" image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png" :description="`${value ? '暂无成员' : '请输入用户名字'}`" />
    </div>

    <!-- 底部 -->
    <div class="bom">
      <div class="info">
        <span>已选择({{ checkList?.length }})：</span>
        <div class="img-w">
          <Image v-for="(item, index) in checkList" :key="index" class="img" width="0.8rem" height="0.8rem" :src="item.img"></Image>
        </div>
      </div>
      <div style="display: flex;align-items: center;">
        <Button @click="back" size="small" class="btn" type="warning"><span>取消</span></Button>
        <Button @click="submitUser" :disabled="checkList.length == 0 || (props.isType == '3' && checkList.length > 1)" size="small" class="btn" type="primary"><span>确 定</span></Button>
      </div>
    </div>
  </div>
</template>

<script setup name="userList">
import { ref } from "vue";
import { Cell, Button, Image, Icon, Checkbox, Search, Empty } from "vant";

import { getUserList } from "@/api/index";

const props = defineProps({
  isType: String,
});

// 人员列表
const userList = ref([]);

// 获取人员列表
const getUserByName = async (name) => {
  const { data } = await getUserList({ name });
  userList.value = data;
};

// 查询value
const value = ref("");
const search = (e) => {
  getUserByName(e);
};

// 选择当前user
const checkList = ref([]);
const setDeptItem = (obj) => {
  // 判断对象是否存在于数组中
  let index = checkList.value.findIndex((item) => item.userId === obj.userId);
  if (index !== -1) {
    // 对象存在于数组中，删除该对象
    checkList.value.splice(index, 1);
  } else {
    // 对象不存在于数组中，添加该对象
    checkList.value.push(obj);
  }
};

// 提交选择的用户
const emit = defineEmits(["callback", "back"]);
const submitUser = () => {
  emit("callback", checkList.value);
  // 清空 只针对分享的时候
  checkList.value = [];
  userList.value = [];
  value.value = "";
};

const back = () => {
  if (props.isType == "3") {
    checkList.value = [];
    userList.value = [];
    value.value = "";
  }
  emit("back");
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
